// pages/order/order.js
let shopCtrl = require('../../utils/shopCtrl');
let {creatOrder} = require('../../api/orderApi');
Page({
  data: {
    address: null,
    orderList: [],
    total: 0,
    price: 0,
  },
  onLoad() {
    this.getSelGoods();
    // let userInfo ={uid:123,token:1234};
    // wx.setStorageSync('userInfo', userInfo);
  },
  setAddress() {
    wx.chooseAddress({
      success: (res) => {
        console.log('地址信息', res);
        this.setData({address: res});
        wx.setStorageSync('address', res);
      },
    })
  },
  getSelGoods(){
    let result = shopCtrl.getSelectGoodS();
    let {total, price} = shopCtrl.getPriceCount();
    let address = wx.getStorageSync('address')
    this.setData({orderList: result,total,price,address});
    console.log(result)
  },
  goPay(){
    wx.showModal({
      title: '请支付',
      content: '测试功能，模拟支付',
      success (res) {
        if (res.confirm) {
          console.log('用户点击确定');
          //将购物车里面已经下单的数据，清除掉
          shopCtrl.rmOrderGoods();
          //跳转到个人页面
          wx.reLaunch({
            url: '/pages/my/my',
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  submitOrder(){
    let {token} = wx.getStorageSync('userInfo');
    if(token){
      console.log('准备提交订单');
      let {address,orderList} = this.data;
      let addressDetail = address.provinceName + address.cityName + address.countyName + address.detailInfo + ',收件人：' + address.userName;
      let goodsList = orderList.map(item => {
        return {
          goodsId : item.gid,
          price : item.gprice,
          image : item.gimgurl,
          count : item.gnum,
          name : item.gtitle
        }
      });
      let obj = {
        "goodsList":goodsList,
        "uid":wx.getStorageSync('userInfo').uid,
        "address":addressDetail,
        "phone":address.telNumber,
      };      
      creatOrder(obj).then(res => {
        console.log('订单添加结果：', res.data);
        if(res.data.code) {
          //添加订单成功，去支付
          this.goPay();
        }
      })
    }else{
      wx.showModal({
        title: '提示',
        content: '您还未登录，请登录',
        success (res) {
          if (res.confirm) {
            console.log('用户点击确定');
            wx.navigateTo({
              url: '/pages/login/login',
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }
  },
})